import trim from 'lodash/trim'
import {WeaTools} from 'ecCom'

export const judgeIsNumber = (val) =>{
    if(val === null || typeof val === "undefined")
        return false;
    const reg = /^(-?\d+)(\.\d+)?$/;
    return reg.test(val.toString());
}

export const convertAmountChinese = (num) =>{
    if(!judgeIsNumber(num))
        return "";
    let amount_convert_unit = "元";
    if(window.WfForm.getReqFormState() && window.WfForm.getReqFormState().getIn(["conf", "propFileCfg", "amount_convert_unit"]) === true)
        amount_convert_unit = "圆";
    if(typeof num === "string")
        num = parseFloat(num);
    var prefh = "";
    if(num < 0) {
        prefh = "负";
        num = Math.abs(num);
    }
    if(num > Math.pow(10, 12))
        return "";
    var cn = "零壹贰叁肆伍陆柒捌玖";
    var unit = new Array("拾佰仟", "分角");
    var unit1 = new Array("万亿万", "");
    var numArray = num.toString().split(".");
    var start = new Array(numArray[0].length - 1, 2);
    function toChinese(num, index) {
        var num = num.replace(/\d/g, function($1) {
            return cn.charAt($1) + unit[index].charAt(start-- % 4 ? start % 4 : -1);
        });
        return num;
    }
    for(var i = 0; i < numArray.length; i++) {
        var tmp = "";
        for(var j = 0; j * 4 < numArray[i].length; j++) {
            var strIndex = numArray[i].length - (j + 1) * 4;
            var str = numArray[i].substring(strIndex, strIndex + 4);
            var start = i ? 2 : str.length - 1;
            var tmp1 = toChinese(str, i);
            tmp1 = tmp1.replace(/(零.)+/g, "零").replace(/零+$/, "");
            tmp = (tmp1 + unit1[i].charAt(j - 1)) + tmp;
        }
        numArray[i] = tmp;
    }
    numArray[1] = numArray[1] ? numArray[1] : "";
    numArray[0] = numArray[0] ? numArray[0] + amount_convert_unit : numArray[0];
    numArray[1] = numArray[1].replace(/^零+/, "");
    numArray[1] = numArray[1].match(/分/) ? numArray[1] : numArray[1] + "整";
    var money = numArray[0] + numArray[1];
    money = money.replace(/(亿万)+/g, "亿");
    if(money == "整") {
        money = "零"+amount_convert_unit+"整";
    } else {
        money = prefh + money;
    }
    return money;
}

export const realLength = (str) => {
	let j = 0;
	for(var i = 0; i <= str.length - 1; i++) {
		j = j + 1;
		if((str.charCodeAt(i)) > 127) {
			j = j + 2;
		}
	}
	return j;
}

export const checkLength =(str,strLen,elMaxLen) =>{
	if(strLen <= elMaxLen) {
		return str;
	}
	
	let j = 0;
	for(var i = 0; i <= str.length - 1; i++) {
		j = j + 1;
		if((str.charCodeAt(i)) > 127) {
			j = j + 2;
		}
		
		if(j > elMaxLen){
			return str.substring(0,i);
		}
		
		if(j == elMaxLen) {
			return str.substring(0,i+1);
		}
	}
	return str;
}

export const convertFloatValue = (realval, decimals, transQfw, transAbs) =>{
	if(!judgeIsNumber(realval))     //非数值直接返回原始值
		return realval;
    realval = realval.toString();
	var formatval = "";
	if(decimals === 0){		//需取整
		formatval = Math.round(parseFloat(realval)).toString();
	}else{
        var n = Math.pow(10, decimals);
        formatval = (Math.round(parseFloat(realval)*n)/n).toString();
		var pindex = formatval.indexOf(".");
		var pointLength = pindex>-1 ? formatval.substr(pindex+1).length : 0;	//当前小数位数
		if(decimals > pointLength){		//需补零
            if(pindex == -1)
			    formatval += ".";
			for(var i=0; i<decimals-pointLength; i++){
				formatval += "0";
			}
		}
	}
	var index = formatval.indexOf(".");
	var intPar = index>-1 ? formatval.substring(0,index) : formatval;
	var pointPar = index>-1 ? formatval.substring(index) : "";
	//取绝对值
	if(transAbs === true){		//取绝对值
		intPar = Math.abs(intPar).toString();
	}
	if(transQfw === true){				//整数位format成千分位
   		var reg1 = /(-?\d+)(\d{3})/;
        while(reg1.test(intPar)) {   
        	intPar = intPar.replace(reg1, "$1,$2");   
        } 
	}
	formatval = intPar + pointPar;
	return formatval;
}

export const convertFormatValue =(realval,formatJSON)=>{
	try{
		var formatval="";
		var numberType=parseInt(formatJSON["numberType"]);
		if(numberType===1){			//1常规
		}else if(numberType===2){	//2数值
			const transQfw = parseInt(formatJSON["thousands"]||0) === 1;
			const transAbs = formatJSON["formatPattern"] == "3" || formatJSON["formatPattern"] == "4";
			if(parseInt(formatJSON["decimals"]) < 0 ){
				return realval;
			}
			formatval = convertFloatValue(realval, parseInt(formatJSON["decimals"]), transQfw, transAbs);
		}else if(numberType===3){	//3日期
			//formatval = this.formatToDate(realval,formatJSON["formatPattern"]);
			formatval = WeaTools.formatDate(realval,formatJSON["formatPattern"]);
		}else if(numberType===4){	//4时间
			//formatval = this.formatToTime(realval,formatJSON["formatPattern"]);
			formatval = WeaTools.formatTime(realval,formatJSON["formatPattern"]);
		}else if(numberType===5){	//5百分比
			formatval = formatToPercent(realval,formatJSON["decimals"]);
		}else if(numberType===6){	//6科学计数
			formatval = formatToScience(realval,formatJSON["decimals"]);
		}else if(numberType===7){	//7文本
		}else if(numberType===8){	//8特殊
			formatval = formatToSpecial(realval,formatJSON["formatPattern"]);
		}
		return formatval;
	}catch(e){
		if(window.console)	console.log("format error:"+ e);
		return realval;
	}
}

export const formatToDate =(realVal,formatPattern) =>{
	const pattern  =  new RegExp("^\\d{2,4}-\\d{1,2}-\\d{1,2}$");
	if(!pattern.test(realVal)){
		return realVal;
	}
	/**
	 * formatPattern
	 * 1：yyyy/MM/dd
	 * 2：yyyy-MM-dd
	 * 3：yyyy年MM月dd日
	 * 4：yyyy年MM月
	 * 5：MM月dd日
	 * 6：EEEE
	 * 7：日期大写
	 * 8：yyyy/MM/dd hh:mm a
	 * 9：yyyy/MM/dd HH:mm
	 */
	let arr = realVal.split("-");
	let year =  arr[0];
	let month = arr[1];
	let day = arr[2];
	if(parseInt(month) > 12 || parseInt(day) > 31 || parseInt(year) <= 0 || parseInt(month) <= 0 || parseInt(day) <= 0){
		return realVal;
	}
	if(year.length == 2) year = "00"+year;
	if(year.length == 3) year = "0"+year;
	if(month.length == 1) month = "0"+month;
	if(day.length == 1) day = "0"+day;
	realVal = year + "-" + month + "-" + day;
	if(new Date(realVal).toString().indexOf("undefined") > -1){		//解决IE下类似不存在的日期2014-9-31通过new Date无法生成日期问题，chrome下默认取的下一天
		return realVal;
	}
	
	switch(parseInt(formatPattern)){
		case 1:
			return this.formatDate(new Date(realVal),"yyyy/MM/dd");
		case 2:
			return this.formatDate(new Date(realVal),"yyyy-MM-dd");
		case 3:
			return this.formatDate(new Date(realVal),"yyyy年MM月dd日");
		case 4:
			return this.formatDate(new Date(realVal),"yyyy年MM月");
		case 5:
			return this.formatDate(new Date(realVal),"MM月dd日");
		case 6:
			return this.formatDate(new Date(realVal),"wwww");	
		case 7:
			return this.dataToChinese(new Date(realVal));
		case 8:
			return this.formatDate(new Date(realVal),"yyyy/MM/dd 12:00 a");		
		case 9:
			return this.formatDate(new Date(realVal),"yyyy/MM/dd 00:00");
		default:
			return realVal;
	}
}

export const formatDate = (date, fmt) =>{
	fmt = fmt || 'yyyy-MM-dd HH:mm:ss';
	const obj = {
		'y': date.getFullYear(), // 年份，注意必须用getFullYear
		'M': date.getMonth() + 1, // 月份，注意是从0-11
		'd': date.getDate(), // 日期
		'q': Math.floor((date.getMonth() + 3) / 3), // 季度
		'w': date.getDay(), // 星期，注意是0-6
		'H': 12, // 24小时制
		'h': 12, // 12小时制
		'm': 0, // 分钟
		's': 0, // 秒
		'S': 0, // 毫秒
		'a': 'AM'
	};
	var week = ['天', '一', '二', '三', '四', '五', '六'];
	for(var i in obj){
		fmt = fmt.replace(new RegExp(i+'+', 'g'), function(m){
			var val = obj[i] + '';
			if(i == 'a') return val;
			if(i == 'w') return (m.length > 2 ? '星期' : '周') + week[val];
			for(var j = 0, len = val.length; j < m.length - len; j++) val = '0' + val;
			return m.length == 1 ? val : val.substring(val.length - m.length);
		});
	}
	return fmt;
}

export const dataToChinese=(date) =>{
	const arr =  ["〇", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
	let year  = date.getFullYear();
	let month = date.getMonth() + 1;
	let day = date.getDate();
	let tempYear = year.toString().split('').map((o)=>{
		return arr[parseInt(o)];
	}).toString();
	return (tempYear + "年" + convertNumToChinese(month) + "月" + convertNumToChinese(day) + "日").replace(/\,/g,'');
}

export const convertNumToChinese=(num)=>{
	const arr1 = ["", "", "二", "三"];
	const arr2 = ["", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
	num = num<10 ? "0"+num.toString() : num.toString();
	const first = parseInt(num.toString().split("")[0]);
	const second = parseInt(num.toString().split("")[1]);
	return arr1[first] + (first > 0 ? "十" : "") + arr2[second];
}

export const formatToTime=(realVal,formatPattern)=>{
	const pattern  =  new RegExp("^(\\d{1,2}:\\d{1,2})(:\\d{1,2})?$");
	if(!pattern.test(realVal)){
		return realVal;
	}
	/**
	 * formatPattern
	 * 1：HH:MI:SS
	 * 2：HH:MI:SS AM/PM
	 * 3：HH:MI
	 * 4：HH:MI AM/PM
	 * 5：HH时MI分SS秒
	 * 6：HH时MI分
	 * 7：HH时MI分SS秒 AM/PM
	 * 8：HH时MI分 AM/PM
	 **/
	const realValArr = realVal.split(":");
	const hour  = realValArr[0];
	const minute = realValArr[1];
	const separatorChar = ":";
	const suffix  = parseInt(hour) < 12 ? " AM":" PM";
	switch(parseInt(formatPattern)){
		case 1:
			return hour + separatorChar +  minute + separatorChar + "00";
		case 2:
			return hour + separatorChar +  minute + separatorChar + "00" +　suffix;
		case 3:
			return hour + separatorChar +  minute;
		case 4:
			return hour + separatorChar +  minute + suffix;
		case 5:
			return hour + "时" + minute + "分00秒"; 
		case 6:
			return hour + "时" + minute + "分";
		case 7:
			return hour + "时" + minute + "分00秒" + suffix;
		case 8:
			return hour + "时" + minute + "分" + suffix;
		default:
			return realVal;
	}
}

export const formatToPercent=(realVal,decimals)=>{	//转百分比
	const pattern  =  new RegExp("^(-?\\d+)(\\.\\d+)?$");
	if(!pattern.test(realVal)){
		return realVal;
	}
	return convertFloatValue(Number(realVal) * 100,parseInt(decimals),false) + "%";
}

export const formatToScience=(realVal,decimals)=>{	//转科学计数
	const pattern  =  new RegExp("^(-?\\d+)(\\.\\d+)?$");
	if(!pattern.test(realVal)){
		return realVal;
	}
	let result = Number(realVal).toExponential(decimals).toUpperCase();
	result = result.replace(/E(\+|-)(\d){1}$/, "E$10$2");	//补零
	return result;
}

export const formatToSpecial=(realVal,formatPattern)=>{
	const pattern  =  new RegExp("^(-?\\d{1,12})(\\.\\d+)?$");
	if(!pattern.test(realVal)){
		return realVal;
	}
	if(parseInt(formatPattern) === 1){
		const digit = ["〇", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
		const unit = [["", "万", "亿"],["", "十", "百", "千"]];
		return specialTrans(realVal,digit,unit);
	}else{
		const digit = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
		const unit = [["", "万", "亿"],["", "拾", "佰", "千"]];
		return specialTrans(realVal,digit,unit);
	}
}

export const specialTrans=(realVal,digit,unit)=>{
	realVal = parseFloat(realVal).toString();
	if(parseFloat(realVal) === 0){
		return digit[0];
	}
	let headfix = "";
	let intPar_t = "";
	let pointPar_t = "";
	
	if(parseFloat(realVal) < 0){
		realVal = realVal.substring(1);		
		headfix = "-";
	}
	let realValArr = realVal.split(".");
	let intPar  = trim(realValArr[0]);
	while(intPar.length > 0 && parseInt(intPar[0]) === 0 ){
		intPar = intPar.substr(1);
	}
	let pointPar = realValArr.length === 2 ? trim(realValArr[1]) : "";
	let lastflag =  false;
	let intParArr = intPar.length > 0 ? intPar.toString().split('') : [];
	let pointParArr = pointPar.length > 0 ? pointPar.toString().split(''):[];
	let j = 0;
	
	pointPar_t = pointPar.length > 0 ? "." : pointPar_t;
	pointParArr.map(v=>{
		pointPar_t = pointPar_t + digit[parseInt(v)];
	});
	
	for(let i=intParArr.length - 1;i >= 0 ;i--,j++ ){
		let v = parseInt(intParArr[i]);
		let m  = j%4;
		if(m === 0){
			lastflag = false;
			intPar_t = unit[0][j/4]+intPar_t;
		}
		
		if(v === 0){
			if(lastflag && intPar_t[0] === digit[0]) {
				intPar_t = digit[v]+intPar_t;
			}
		}else{
			lastflag = true;
			intPar_t = digit[v] + unit[1][m] + intPar_t;
		}
	}
	intPar_t = trim(intPar_t).length === 0 ? digit[0] : intPar_t;
	return headfix + intPar_t + pointPar_t;
}